﻿Imports System.IO
Imports System.Xml
Imports System.Windows.Forms
Imports TvDatabase
Imports TvLibrary.Log
Imports TvLibrary.Interfaces
Imports Gentle.Framework

Namespace SetupTv.Sections

    Public Class Setup
        Inherits Global.SetupTv.SectionSettings

#Region "Controls"
        Friend WithEvents TabControl1 As System.Windows.Forms.TabControl
        Friend WithEvents TabPage1 As System.Windows.Forms.TabPage
        Friend WithEvents TabPage2 As System.Windows.Forms.TabPage
        Friend WithEvents Label3 As System.Windows.Forms.Label
        Friend WithEvents ComboBox1 As System.Windows.Forms.ComboBox
        Friend WithEvents ProgressBarLabel As System.Windows.Forms.Label
        Friend WithEvents ProgressBar1 As System.Windows.Forms.ProgressBar
        Friend WithEvents RichTextBox1 As System.Windows.Forms.RichTextBox
        Friend WithEvents Label1 As System.Windows.Forms.Label
        Friend WithEvents tvwStations As System.Windows.Forms.TreeView
        Friend WithEvents btnAddChannels As System.Windows.Forms.Button
        Friend WithEvents TabPage3 As System.Windows.Forms.TabPage
        Friend WithEvents ProgressBar2 As System.Windows.Forms.ProgressBar
        Friend WithEvents rtbImportProgress As System.Windows.Forms.RichTextBox
        Friend WithEvents cbxEdit As System.Windows.Forms.CheckBox
        Friend WithEvents cbxToggle As System.Windows.Forms.CheckBox
        Friend WithEvents Label2 As System.Windows.Forms.Label
        Friend WithEvents cbxWarn As System.Windows.Forms.CheckBox
        Friend WithEvents LinkLabel1 As System.Windows.Forms.LinkLabel
        Friend WithEvents LinkLabel2 As System.Windows.Forms.LinkLabel

#End Region

        Public Sub New()
            InitializeComponent()
        End Sub

        Private Sub InitializeComponent()
            Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Setup))
            Me.TabControl1 = New System.Windows.Forms.TabControl()
            Me.TabPage1 = New System.Windows.Forms.TabPage()
            Me.RichTextBox1 = New System.Windows.Forms.RichTextBox()
            Me.LinkLabel2 = New System.Windows.Forms.LinkLabel()
            Me.LinkLabel1 = New System.Windows.Forms.LinkLabel()
            Me.Label3 = New System.Windows.Forms.Label()
            Me.ComboBox1 = New System.Windows.Forms.ComboBox()
            Me.ProgressBarLabel = New System.Windows.Forms.Label()
            Me.ProgressBar1 = New System.Windows.Forms.ProgressBar()
            Me.Label1 = New System.Windows.Forms.Label()
            Me.TabPage2 = New System.Windows.Forms.TabPage()
            Me.Label2 = New System.Windows.Forms.Label()
            Me.cbxWarn = New System.Windows.Forms.CheckBox()
            Me.cbxToggle = New System.Windows.Forms.CheckBox()
            Me.cbxEdit = New System.Windows.Forms.CheckBox()
            Me.btnAddChannels = New System.Windows.Forms.Button()
            Me.tvwStations = New System.Windows.Forms.TreeView()
            Me.TabPage3 = New System.Windows.Forms.TabPage()
            Me.ProgressBar2 = New System.Windows.Forms.ProgressBar()
            Me.rtbImportProgress = New System.Windows.Forms.RichTextBox()
            Me.TabControl1.SuspendLayout()
            Me.TabPage1.SuspendLayout()
            Me.TabPage2.SuspendLayout()
            Me.TabPage3.SuspendLayout()
            Me.SuspendLayout()
            '
            'TabControl1
            '
            Me.TabControl1.Controls.Add(Me.TabPage1)
            Me.TabControl1.Controls.Add(Me.TabPage2)
            Me.TabControl1.Controls.Add(Me.TabPage3)
            Me.TabControl1.Location = New System.Drawing.Point(4, 3)
            Me.TabControl1.Name = "TabControl1"
            Me.TabControl1.SelectedIndex = 0
            Me.TabControl1.Size = New System.Drawing.Size(479, 418)
            Me.TabControl1.TabIndex = 2
            '
            'TabPage1
            '
            Me.TabPage1.Controls.Add(Me.RichTextBox1)
            Me.TabPage1.Controls.Add(Me.LinkLabel2)
            Me.TabPage1.Controls.Add(Me.LinkLabel1)
            Me.TabPage1.Controls.Add(Me.Label3)
            Me.TabPage1.Controls.Add(Me.ComboBox1)
            Me.TabPage1.Controls.Add(Me.ProgressBarLabel)
            Me.TabPage1.Controls.Add(Me.ProgressBar1)
            Me.TabPage1.Controls.Add(Me.Label1)
            Me.TabPage1.Location = New System.Drawing.Point(4, 22)
            Me.TabPage1.Name = "TabPage1"
            Me.TabPage1.Padding = New System.Windows.Forms.Padding(3)
            Me.TabPage1.Size = New System.Drawing.Size(471, 392)
            Me.TabPage1.TabIndex = 0
            Me.TabPage1.Text = "Welcome"
            Me.TabPage1.UseVisualStyleBackColor = True
            '
            'RichTextBox1
            '
            Me.RichTextBox1.BorderStyle = System.Windows.Forms.BorderStyle.None
            Me.RichTextBox1.Cursor = System.Windows.Forms.Cursors.Default
            Me.RichTextBox1.Font = New System.Drawing.Font("Microsoft Sans Serif", 10.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.RichTextBox1.Location = New System.Drawing.Point(7, 32)
            Me.RichTextBox1.Name = "RichTextBox1"
            Me.RichTextBox1.ScrollBars = System.Windows.Forms.RichTextBoxScrollBars.None
            Me.RichTextBox1.Size = New System.Drawing.Size(458, 210)
            Me.RichTextBox1.TabIndex = 1
            Me.RichTextBox1.Text = resources.GetString("RichTextBox1.Text")
            '
            'LinkLabel2
            '
            Me.LinkLabel2.AutoSize = True
            Me.LinkLabel2.Font = New System.Drawing.Font("Microsoft Sans Serif", 10.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.LinkLabel2.Location = New System.Drawing.Point(6, 245)
            Me.LinkLabel2.Name = "LinkLabel2"
            Me.LinkLabel2.Size = New System.Drawing.Size(159, 17)
            Me.LinkLabel2.TabIndex = 7
            Me.LinkLabel2.TabStop = True
            Me.LinkLabel2.Text = "Using MediaPortal radio"
            '
            'LinkLabel1
            '
            Me.LinkLabel1.AutoSize = True
            Me.LinkLabel1.Font = New System.Drawing.Font("Microsoft Sans Serif", 10.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.LinkLabel1.Location = New System.Drawing.Point(6, 265)
            Me.LinkLabel1.Name = "LinkLabel1"
            Me.LinkLabel1.Size = New System.Drawing.Size(136, 17)
            Me.LinkLabel1.TabIndex = 6
            Me.LinkLabel1.TabStop = True
            Me.LinkLabel1.Text = "Using channel logos"
            '
            'Label3
            '
            Me.Label3.AutoSize = True
            Me.Label3.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.Label3.Location = New System.Drawing.Point(6, 320)
            Me.Label3.Name = "Label3"
            Me.Label3.Size = New System.Drawing.Size(100, 16)
            Me.Label3.TabIndex = 5
            Me.Label3.Text = "Select input file:"
            '
            'ComboBox1
            '
            Me.ComboBox1.Font = New System.Drawing.Font("Microsoft Sans Serif", 10.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.ComboBox1.FormattingEnabled = True
            Me.ComboBox1.Location = New System.Drawing.Point(139, 316)
            Me.ComboBox1.Name = "ComboBox1"
            Me.ComboBox1.Size = New System.Drawing.Size(201, 24)
            Me.ComboBox1.TabIndex = 4
            '
            'ProgressBarLabel
            '
            Me.ProgressBarLabel.AutoSize = True
            Me.ProgressBarLabel.Font = New System.Drawing.Font("Microsoft Sans Serif", 10.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.ProgressBarLabel.Location = New System.Drawing.Point(163, 343)
            Me.ProgressBarLabel.Name = "ProgressBarLabel"
            Me.ProgressBarLabel.Size = New System.Drawing.Size(145, 17)
            Me.ProgressBarLabel.TabIndex = 3
            Me.ProgressBarLabel.Text = "Parsing radio stations"
            Me.ProgressBarLabel.Visible = False
            '
            'ProgressBar1
            '
            Me.ProgressBar1.Location = New System.Drawing.Point(6, 363)
            Me.ProgressBar1.Name = "ProgressBar1"
            Me.ProgressBar1.Size = New System.Drawing.Size(458, 23)
            Me.ProgressBar1.TabIndex = 2
            Me.ProgressBar1.Visible = False
            '
            'Label1
            '
            Me.Label1.AutoSize = True
            Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 16.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.Label1.Location = New System.Drawing.Point(99, 3)
            Me.Label1.Name = "Label1"
            Me.Label1.Size = New System.Drawing.Size(207, 26)
            Me.Label1.TabIndex = 0
            Me.Label1.Text = "Web Radio Importer"
            '
            'TabPage2
            '
            Me.TabPage2.Controls.Add(Me.Label2)
            Me.TabPage2.Controls.Add(Me.cbxWarn)
            Me.TabPage2.Controls.Add(Me.cbxToggle)
            Me.TabPage2.Controls.Add(Me.cbxEdit)
            Me.TabPage2.Controls.Add(Me.btnAddChannels)
            Me.TabPage2.Controls.Add(Me.tvwStations)
            Me.TabPage2.Location = New System.Drawing.Point(4, 22)
            Me.TabPage2.Name = "TabPage2"
            Me.TabPage2.Padding = New System.Windows.Forms.Padding(3)
            Me.TabPage2.Size = New System.Drawing.Size(471, 392)
            Me.TabPage2.TabIndex = 1
            Me.TabPage2.Text = "Station selection"
            Me.TabPage2.UseVisualStyleBackColor = True
            '
            'Label2
            '
            Me.Label2.AutoSize = True
            Me.Label2.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.Label2.Location = New System.Drawing.Point(6, 6)
            Me.Label2.Name = "Label2"
            Me.Label2.Size = New System.Drawing.Size(295, 13)
            Me.Label2.TabIndex = 6
            Me.Label2.Text = "Select radio web streams to add as TV Server radio channels"
            '
            'cbxWarn
            '
            Me.cbxWarn.AutoSize = True
            Me.cbxWarn.Checked = True
            Me.cbxWarn.CheckState = System.Windows.Forms.CheckState.Checked
            Me.cbxWarn.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.cbxWarn.Location = New System.Drawing.Point(183, 369)
            Me.cbxWarn.Name = "cbxWarn"
            Me.cbxWarn.Size = New System.Drawing.Size(183, 17)
            Me.cbxWarn.TabIndex = 5
            Me.cbxWarn.Text = "Warn on duplicate channel name"
            Me.cbxWarn.UseVisualStyleBackColor = True
            '
            'cbxToggle
            '
            Me.cbxToggle.AutoSize = True
            Me.cbxToggle.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.cbxToggle.Location = New System.Drawing.Point(395, 6)
            Me.cbxToggle.Name = "cbxToggle"
            Me.cbxToggle.Size = New System.Drawing.Size(72, 17)
            Me.cbxToggle.TabIndex = 4
            Me.cbxToggle.Text = "Toggle all"
            Me.cbxToggle.UseVisualStyleBackColor = True
            '
            'cbxEdit
            '
            Me.cbxEdit.AutoSize = True
            Me.cbxEdit.Checked = True
            Me.cbxEdit.CheckState = System.Windows.Forms.CheckState.Checked
            Me.cbxEdit.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.cbxEdit.Location = New System.Drawing.Point(3, 369)
            Me.cbxEdit.Name = "cbxEdit"
            Me.cbxEdit.Size = New System.Drawing.Size(165, 17)
            Me.cbxEdit.TabIndex = 3
            Me.cbxEdit.Text = "Edit channel names on import"
            Me.cbxEdit.UseVisualStyleBackColor = True
            '
            'btnAddChannels
            '
            Me.btnAddChannels.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Me.btnAddChannels.Location = New System.Drawing.Point(372, 366)
            Me.btnAddChannels.Name = "btnAddChannels"
            Me.btnAddChannels.Size = New System.Drawing.Size(92, 23)
            Me.btnAddChannels.TabIndex = 2
            Me.btnAddChannels.Text = "Import Channels"
            Me.btnAddChannels.UseVisualStyleBackColor = True
            '
            'tvwStations
            '
            Me.tvwStations.CheckBoxes = True
            Me.tvwStations.FullRowSelect = True
            Me.tvwStations.HotTracking = True
            Me.tvwStations.Location = New System.Drawing.Point(0, 25)
            Me.tvwStations.Name = "tvwStations"
            Me.tvwStations.ShowNodeToolTips = True
            Me.tvwStations.Size = New System.Drawing.Size(468, 335)
            Me.tvwStations.TabIndex = 1
            '
            'TabPage3
            '
            Me.TabPage3.Controls.Add(Me.ProgressBar2)
            Me.TabPage3.Controls.Add(Me.rtbImportProgress)
            Me.TabPage3.Location = New System.Drawing.Point(4, 22)
            Me.TabPage3.Name = "TabPage3"
            Me.TabPage3.Size = New System.Drawing.Size(471, 392)
            Me.TabPage3.TabIndex = 2
            Me.TabPage3.Text = "Import progress"
            Me.TabPage3.UseVisualStyleBackColor = True
            '
            'ProgressBar2
            '
            Me.ProgressBar2.Location = New System.Drawing.Point(3, 366)
            Me.ProgressBar2.Name = "ProgressBar2"
            Me.ProgressBar2.Size = New System.Drawing.Size(464, 23)
            Me.ProgressBar2.TabIndex = 1
            '
            'rtbImportProgress
            '
            Me.rtbImportProgress.BorderStyle = System.Windows.Forms.BorderStyle.None
            Me.rtbImportProgress.HideSelection = False
            Me.rtbImportProgress.Location = New System.Drawing.Point(4, 4)
            Me.rtbImportProgress.Name = "rtbImportProgress"
            Me.rtbImportProgress.Size = New System.Drawing.Size(464, 356)
            Me.rtbImportProgress.TabIndex = 0
            Me.rtbImportProgress.Text = ""
            '
            'Setup
            '
            Me.Controls.Add(Me.TabControl1)
            Me.Name = "Setup"
            Me.Size = New System.Drawing.Size(487, 424)
            Me.TabControl1.ResumeLayout(False)
            Me.TabPage1.ResumeLayout(False)
            Me.TabPage1.PerformLayout()
            Me.TabPage2.ResumeLayout(False)
            Me.TabPage2.PerformLayout()
            Me.TabPage3.ResumeLayout(False)
            Me.ResumeLayout(False)

        End Sub

        Public Overrides Sub OnSectionActivated()

            MyBase.OnSectionActivated()
            Log.Info("WebRadio: Activated")

            TabControl1.SelectedIndex = 0
            ComboBox1.Items.Clear()
            tvwStations.Nodes.Clear()
            rtbImportProgress.Text = ""
            ProgressBar2.Value = 0
            LoadCountries()

        End Sub

        Public Overrides Sub OnSectionDeActivated()
            MyBase.OnSectionDeActivated()
            Log.Info("WebRadio: DeActivated")

        End Sub

        Private Sub LoadCountries()

            Dim folder As String = String.Format("{0}\team mediaportal\mediaportal tv server\webradio\", Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData))
            Dim di As DirectoryInfo = New DirectoryInfo(folder)
            Dim files As FileSystemInfo() = di.GetFileSystemInfos("*.xml")
            ComboBox1.Items.Clear()
            For Each File As FileSystemInfo In files
                ComboBox1.Items.Add(Path.GetFileNameWithoutExtension(File.FullName))
            Next

        End Sub

        Private Sub LoadTreeview(ByVal countryCode As String)

            Dim stations As New List(Of Station)
            stations = GetStations(countryCode)

            If stations.Count = 0 Then Exit Sub

            ProgressBar1.Maximum = stations.Count
            ProgressBar1.Visible = True
            ProgressBarLabel.Visible = True

            tvwStations.BeginUpdate()
            tvwStations.Nodes.Clear()

            Dim i As Integer = 0
            Dim j As Integer = 0
            Dim layer As New TvBusinessLayer
            Dim stationNames As New List(Of String)
            Dim currentNode As TreeNode = Nothing
            For Each station As Station In stations

                If stationNames.Contains(station.stationName) Then
                    For Each node As TreeNode In tvwStations.Nodes
                        If node.Text = station.stationName Then
                            currentNode = node
                            Exit For
                        End If
                    Next
                Else
                    'tvwStations.Nodes.Add(New TreeNode(station.stationName))
                    Dim tn As New TreeNode
                    tn.Text = station.stationName
                    tn.ToolTipText = String.Format("{0}{1}{2}", station.location, vbCrLf, station.genre)
                    currentNode = tn
                    If Len(station.url1) > 0 Then currentNode.Nodes.Add(New TreeNode(station.url1))
                    If Len(station.url2) > 0 Then currentNode.Nodes.Add(New TreeNode(station.url2))
                    If Len(station.url3) > 0 Then currentNode.Nodes.Add(New TreeNode(station.url3))
                    If Len(station.url4) > 0 Then currentNode.Nodes.Add(New TreeNode(station.url4))
                    If Len(station.url5) > 0 Then currentNode.Nodes.Add(New TreeNode(station.url5))
                    If Len(station.url6) > 0 Then currentNode.Nodes.Add(New TreeNode(station.url6))
                    If Len(station.url7) > 0 Then currentNode.Nodes.Add(New TreeNode(station.url7))
                    If Len(station.url8) > 0 Then currentNode.Nodes.Add(New TreeNode(station.url8))
                    If Len(station.url9) > 0 Then currentNode.Nodes.Add(New TreeNode(station.url9))
                    If Len(station.url10) > 0 Then currentNode.Nodes.Add(New TreeNode(station.url10))
                    stationNames.Add(station.stationName)
                    If tn.Nodes.Count > 0 Then tvwStations.Nodes.Add(tn)
                End If

                i += 1
                ProgressBar1.Value = i

                j += 1
                If j = 50 Then
                    Application.DoEvents()
                    j = 0
                End If

            Next

            tvwStations.EndUpdate()
            TabControl1.SelectedIndex = 1
            ProgressBar1.Value = 0
            ProgressBar1.Visible = False
            ProgressBarLabel.Visible = False

        End Sub

        Private Function GetStations(ByVal countryCode As String) As List(Of Station)

            Dim filename As String = String.Format("{0}\team mediaportal\mediaportal tv server\webradio\{1}.xml", Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), countryCode)

            Dim xmlDoc As New XmlDocument
            If File.Exists(filename) Then
                Try
                    xmlDoc.Load(filename)
                Catch ex As XmlException
                    Log.Error("WebRadio: Error loading xml. {0}", ex.Message)
                    MessageBox.Show(String.Format("WebRadio: Error loading xml. {0}", ex.Message), "WebRadioImport XML Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                End Try
            Else
                'Error cannot find file
                Log.Error("WebRadio: Cannot find file {0}", filename)
            End If

            Dim stations As New List(Of Station)
            Dim nodes As XmlNodeList = xmlDoc.SelectNodes("/webradio/country/station")

            For Each node As XmlNode In nodes
                Try
                    Dim station As New Station
                    station.stationName = node.Attributes("name").Value
                    station.location = node.Attributes("location").Value
                    station.genre = node.Attributes("genre").Value
                    station.url1 = node.Attributes("url1").Value
                    If Not node.Attributes.ItemOf("url2") Is Nothing Then station.url2 = node.Attributes("url2").Value
                    If Not node.Attributes.ItemOf("url3") Is Nothing Then station.url3 = node.Attributes("url3").Value
                    If Not node.Attributes.ItemOf("url4") Is Nothing Then station.url4 = node.Attributes("url4").Value
                    If Not node.Attributes.ItemOf("url5") Is Nothing Then station.url5 = node.Attributes("url5").Value
                    If Not node.Attributes.ItemOf("url6") Is Nothing Then station.url6 = node.Attributes("url6").Value
                    If Not node.Attributes.ItemOf("url7") Is Nothing Then station.url7 = node.Attributes("url7").Value
                    If Not node.Attributes.ItemOf("url8") Is Nothing Then station.url8 = node.Attributes("url8").Value
                    If Not node.Attributes.ItemOf("url9") Is Nothing Then station.url9 = node.Attributes("url9").Value
                    If Not node.Attributes.ItemOf("url10") Is Nothing Then station.url10 = node.Attributes("url10").Value
                    stations.Add(station)
                Catch ex As Exception
                    Log.Error("WebRadio: Cannot add {0} - check XML has correct attributes, name, url1, url2, url3", filename)
                End Try

            Next

            stations.Sort(New StationNameComparer)

            Return stations

        End Function

        Private Sub tvwStations_AfterCheck(sender As System.Object, e As System.Windows.Forms.TreeViewEventArgs) Handles tvwStations.AfterCheck

            If e.Action = TreeViewAction.ByKeyboard OrElse e.Action = TreeViewAction.ByMouse Then
                CheckUnCheckNodes(e.Node)
            End If

        End Sub

        Private Sub tvwStations_DoubleCLick(sender As System.Object, e As System.Windows.Forms.TreeViewEventArgs) Handles tvwStations.DoubleClick

            If e.Action = TreeViewAction.ByKeyboard OrElse e.Action = TreeViewAction.ByMouse Then
                CheckUnCheckNodes(e.Node)
            End If

        End Sub

        Private Sub CheckUnCheckNodes(ByVal node As TreeNode)
            If node.Parent Is Nothing Then
                For Each child As TreeNode In node.Nodes
                    child.Checked = node.Checked
                Next
            Else
                Dim parentChecked As Boolean = False
                For Each child As TreeNode In node.Parent.Nodes
                    If child.Checked Then parentChecked = True
                Next
                node.Parent.Checked = parentChecked
            End If
        End Sub

        Private Sub cbxToggle_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles cbxToggle.CheckedChanged

            Dim checked As Boolean = cbxToggle.Checked

            For Each node As TreeNode In tvwStations.Nodes
                node.Checked = checked
                If node.Parent Is Nothing Then
                    For Each child As TreeNode In node.Nodes
                        child.Checked = checked
                    Next
                End If
            Next

        End Sub

        Private Sub ComboBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
            Application.DoEvents()
            LoadTreeview(ComboBox1.SelectedItem)
        End Sub

        Private Sub btnAddChannels_Click(sender As System.Object, e As System.EventArgs) Handles btnAddChannels.Click

            TabControl1.SelectedIndex = 2

            Dim i As Integer = 0
            Dim j As Integer = 0

            For Each node As TreeNode In tvwStations.Nodes
                If node.Parent Is Nothing Then
                    For Each child As TreeNode In node.Nodes
                        If child.Checked Then i += 1
                    Next
                End If
            Next
            ProgressBar2.Maximum = i
            ProgressBar2.Value = 0

            If i = 0 Then
                MessageBox.Show("You have not selected any radio channels to import.", "Web Radio Station Selector", MessageBoxButtons.OK)
                TabControl1.SelectedIndex = 1
                Exit Sub
            Else
                If MessageBox.Show(String.Format("You are about to import {0} radio channels, do you want to continue?", i.ToString), "Web Radio Station Selector", MessageBoxButtons.YesNo) = DialogResult.No Then
                    TabControl1.SelectedIndex = 1
                    Exit Sub
                End If
            End If

            Dim channelName As String = String.Empty
            Dim url As String = String.Empty
            i = 0

            Log.Info("WebRadio: Add channels started {0}", Now.ToString)

            For Each node As TreeNode In tvwStations.Nodes
                If (node.Parent Is Nothing) And (node.Checked) Then
                    For Each child As TreeNode In node.Nodes
                        If child.Checked Then
                            channelName = node.Text
                            If DoesChannelNameExist(channelName) And cbxWarn.Checked Then
                                channelName = InputBox(String.Format("Channel {0} already exists, enter a new name or click OK to accept a duplicate channel name.", channelName), "Duplicate Channel Name", channelName)
                            Else
                                If cbxEdit.Checked Then channelName = InputBox(String.Format("Edit channel name (if required).", channelName), "Edit Channel Name", channelName)
                            End If
                            url = child.Text

                            If channelName <> "" And node.Text <> "" Then
                                If AddWebRadioChannel(channelName, url) Then
                                    rtbImportProgress.AppendText(String.Format("Added {0} - {1}{2}", channelName, url, vbCrLf))
                                    Log.Info("WebRadio: Added {0} - {1}", channelName, url)
                                Else
                                    Log.Error("Failed to add {0} - {1}", channelName, url)
                                    Dim start, finish As Integer
                                    start = rtbImportProgress.TextLength
                                    rtbImportProgress.AppendText(String.Format("Failed to add {0} - {1}{2}", channelName, url, vbCrLf))
                                    finish = rtbImportProgress.TextLength
                                    rtbImportProgress.Select(start, finish - start)
                                    rtbImportProgress.SelectionColor = Drawing.Color.Red
                                End If
                            End If
                            i += 1
                            ProgressBar2.Value = i
                        End If
                    Next
                End If

                rtbImportProgress.SelectionStart = rtbImportProgress.TextLength

                j += 1
                If j = 20 Then
                    Application.DoEvents()
                    j = 0
                End If
            Next

            rtbImportProgress.AppendText("Done.")
            rtbImportProgress.SelectionStart = rtbImportProgress.TextLength
            Log.Info("WebRadio: Add channels completed {0}", Now.ToString)

        End Sub

        Private Function DoesChannelNameExist(ByVal name As String) As Boolean

            Dim channels As List(Of Channel) = Channel.ListAll

            For Each c As Channel In channels
                If c.IsRadio And (c.DisplayName.ToLower = name.ToLower) Then Return True
            Next

            Return False

        End Function

        Private Function AddWebRadioChannel(ByVal name As String, ByVal url As String) As Boolean

            Try
                'Dim channel As New Channel(name, True, False, 0, Schedule.MinSchedule, False, Schedule.MinSchedule, 10000, True, "", True, name)
                Dim channel As New Channel(True, False, 0, Schedule.MinSchedule, False, Schedule.MinSchedule, 10000, False, "", name)
                channel.Persist()
                Dim layer As New TvBusinessLayer()
                layer.AddWebStreamTuningDetails(channel, url, 0)
                layer.AddChannelToRadioGroup(channel, TvConstants.RadioGroupNames.AllChannels)
            Catch ex As Exception
                Log.Error("WebRadio: Error adding web station {0} {1}", name, url)
                Return False
            End Try

            Log.Info("WebRadio: Added web station {0} {1}", name, url)
            Return True

        End Function

        Private Sub LinkLabel1_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
            System.Diagnostics.Process.Start("http://wiki.team-mediaportal.com/1_MEDIAPORTAL_1/15_Customization/92_Logos/1_Channel_Logos")
        End Sub

        Private Sub LinkLabel2_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel2.LinkClicked
            System.Diagnostics.Process.Start("http://wiki.team-mediaportal.com/1_MEDIAPORTAL_1/14_Using_MediaPortal/4_Radio")
        End Sub

    End Class

    Public Class StationNameComparer
        Implements IComparer(Of Station)
        Public Overridable Overloads Function Compare(ByVal x As Station, ByVal y As Station) As Integer Implements IComparer(Of Station).Compare
            Return x.stationName.ToLower.CompareTo(y.stationName.ToLower)
        End Function
    End Class

End Namespace
